package com.ali.sqlSession;

import com.ali.pogo.Configuration;
import com.ali.pogo.MappedStatement;

import java.util.List;

public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }


    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws Exception {
        SimpleExcutor simpleExcutor = new SimpleExcutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        List<Object> query = simpleExcutor.query(configuration, mappedStatement, params);

        return (List<E>) query;
    }

    @Override
    public Configuration getConfiguration() {
        return this.configuration;
    }

    @Override
    public <T> T getMapper(Class<T> type) throws Exception {
        return this.configuration.getMapper(type, this);
    }

    @Override
    public int insert(String statement, Object[] parameter) {
        return this.update1(statement, parameter[0]);
    }

    @Override
    public int update(String statement, Object[] parameter) {
        return this.update1(statement, parameter[0]);
    }

    @Override
    public int delete(String statement, Object[] parameter) {
        MappedStatement mappedStatement = this.configuration.getMappedStatementMap().get(statement);
        SimpleExcutor simpleExcutor = new SimpleExcutor();
        return simpleExcutor.delete(this.configuration, mappedStatement, parameter[0]);
    }

    private int update1(String statement, Object parameter) {
        MappedStatement mappedStatement = this.configuration.getMappedStatementMap().get(statement);
        SimpleExcutor simpleExcutor = new SimpleExcutor();
        int update = simpleExcutor.update(this.configuration, mappedStatement, parameter);
        return update;
    }
}
